#encoding:utf-8
from flask import Flask,render_template,request,redirect,url_for,session,g
import config
from models import User,Question,Answer
from exts import db
from decorators import login_requisite
from sqlalchemy import or_

app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)



@app.route('/')
def index():
    content={
        'questions':Question.query.order_by('-create_time').all()
    }
    return render_template('index.html',**content)

@app.route('/login/',methods=['GET','POST'])
def login():
    if request.method=='GET':
        return render_template('login.html')
    else:
        telephone = request.form.get('telephone')
        password = request.form.get('password')

        user = User.query.filter(User.telephone==telephone).first()
        if user and user.check_password(password):
            session['user_id']=user.id
            #cookie 31天有效
            session.permanent=True
            return redirect(url_for('index'))
        else:
            return u'手机号或者密码错误，请重新输入！'

@app.route('/regist/',methods=['GET','POST'])
def regist():
    if request.method == 'GET':
        return render_template('regist.html')
    else:
        username = request.form.get('username')
        telephone = request.form.get('telephone')
        password1 = request.form.get('password1')
        password2 = request.form.get('password2')

        user = User.query.filter(User.telephone == telephone).first()
        if user:
            return u'该手机号码已经被注册，请换一个手机号注册！'
        else:
            if password1 != password2:
                return u'输入的两个密码不一致，请重新输入！'
            else:
                print 'user.username:%s'% username
                user2 = User(telephone=telephone,username=username,password=password2)
                db.session.add(user2)
                db.session.commit()

                return redirect(url_for('login'))

@app.route('/logout/')
def logout():
    session.pop('user_id')
    # del session['user_id']
    # session.clear()
    return redirect(url_for('login'))

@app.route('/question/',methods=['GET','POST'])
@login_requisite
def question():
    if request.method == 'GET':
        return render_template('question.html')
    else:

        title = request.form.get('title')
        content = request.form.get('content')
        question0 = Question(title = title,content=content)
        question0.author=g.user
        db.session.add(question0)
        db.session.commit()
        return redirect(url_for('index'))



#问答详情页
@app.route('/detail/<question_id>')
def detail(question_id):

    question_model = Question.query.filter(Question.id==question_id).first()

    return render_template('detail.html',question=question_model)

#评论
@app.route('/add_answer/',methods=['GET','POST'])
@login_requisite
def add_answer():
    answer_content = request.form.get('answer-content')
    answer0 = Answer(content=answer_content)
    answer0.author=g.user
    question_id = request.form.get('question_id')
    question0 = Question.query.filter(Question.id==question_id).first()
    answer0.question=question0
    db.session.add(answer0)
    db.session.commit()

    return redirect(url_for('detail',question_id=question_id))

#搜索
@app.route('/search/')
def search():
    p = request.args.get('p')
    #'或'查询
    contents = Question.query.filter(or_(Question.title.contains(p),Question.content.contains(p))).order_by('-create_time')
    #'与'查询
    #contents = Question.query.filter((Question.title.contains(p),Question.content.contains(p))).order_by('-create_time')

    return render_template('index.html',questions=contents)

#钩子函数,上下文处理器，执行的时机在return前
@app.context_processor
def my_context_processor():
    if hasattr(g,'user'):
        return {'user':g.user}
    #如果没有值，要传空字典过去
    return {}

# before_request -> 视图函数 -> 上下文处理器 -> return
#钩子函数，执行的时机在请求接收前
@app.before_request
def my_before_request():
    user_id = session.get('user_id')
    if user_id:
        user = User.query.filter(User.id==user_id).first()
        if user:
            g.user = user

if __name__ == '__main__':
    app.run()
